package com.qiyi.cupid.adplayer
{
   import flash.display.Sprite;
   import flash.events.IEventDispatcher;
   import flash.display.DisplayObjectContainer;
   import flash.display.Loader;
   import flash.net.URLLoader;
   import flash.net.URLRequest;
   import com.qiyi.cupid.adplayer.model.AdBlockedBlackScreen;
   import com.qiyi.cupid.adplayer.events.AdPlayerEvent;
   import com.qiyi.cupid.adplayer.base.Log;
   import com.qiyi.cupid.adplayer.utils.CupidAdPlayerConstants;
   import com.qiyi.cupid.adplayer.utils.CupidAdPlayerUtils;
   import flash.net.URLLoaderDataFormat;
   import flash.utils.setTimeout;
   import flash.events.Event;
   import flash.events.IOErrorEvent;
   import flash.events.SecurityErrorEvent;
   import flash.utils.ByteArray;
   import flash.system.LoaderContext;
   import flash.system.ApplicationDomain;
   import com.qiyi.cupid.adplayer.events.AdBlockedBlackScreenEvent;
   import flash.utils.clearTimeout;
   import com.qiyi.cupid.adplayer.base.CupidParam;
   import com.qiyi.cupid.adplayer.view.DisplayProperties;
   
   public class CupidAdPlayer extends Sprite
   {
      
      public function CupidAdPlayer(param1:CupidParam) {
         super();
         Log.info("init, version=" + VERSION + ", " + param1.toString());
         this._videoPlayerVersion = param1.videoPlayerVersion;
         this._videoId = param1.videoId;
         this._tvId = param1.tvId;
         this._channelId = param1.channelId;
         this._collectionId = param1.collectionId;
         this._playerId = param1.playerId;
         this._albumId = param1.albumId;
         this._userId = param1.userId;
         this._webEventId = param1.webEventId;
         this._videoEventId = param1.videoEventId;
         this._vipRight = param1.vipRight;
         this._terminal = param1.terminal;
         this._duration = param1.duration;
         this._passportId = param1.passportId;
         this._passportCookie = param1.passportCookie;
         this._passportKey = param1.passportKey;
         if(this.isQiyiWebEx())
         {
            this._playerUrl = this.IQIYI_WEBEX_AM_URL;
         }
         else if(param1.playerUrl)
         {
            this._playerUrl = param1.playerUrl;
         }
         else
         {
            this._playerUrl = this.IQIYI_WEB_AM_URL;
         }
         
         if(param1.dispatcher == null)
         {
            this._dispatcher = this;
         }
         else
         {
            this._dispatcher = param1.dispatcher;
         }
         this._volume = param1.volume;
         this._videoIndex = param1.videoIndex;
         this._stageWidth = param1.stageWidth;
         this._stageHeight = param1.stageHeight;
         this._displayContainer = param1.adContainer;
         this._screenStatus = DisplayProperties.isFullScreen(this._displayContainer.stage)?"1":"0";
         this._baiduMainVideo = param1.baiduMainVideo;
         this._disablePreroll = param1.disablePreroll;
         this._disableSkipAd = param1.disableSkipAd;
         this._enableVideoCore = param1.enableVideoCore;
         this._isUGC = param1.isUGC;
         this._videoPlayerUrl = this._displayContainer.loaderInfo?this._displayContainer.loaderInfo.loaderURL:"";
         this._env = this.generateEnv();
         this.addAdPlayerEventListeners();
      }
      
      public static const VERSION:String = "2.1.6";
      
      private var _tvId:String;
      
      private var _videoId:String;
      
      private var _albumId:String;
      
      private var _channelId:uint;
      
      private var _collectionId:String;
      
      private var _webEventId:String;
      
      private var _videoEventId:String;
      
      private var _userId:String;
      
      private var _vipRight:String;
      
      private var _terminal:String;
      
      private var _duration:Number;
      
      private var _passportId:String;
      
      private var _passportCookie:String;
      
      private var _passportKey:String;
      
      private var _enableVideoCore:Boolean;
      
      private var _isUGC:Boolean;
      
      private var _dispatcher:IEventDispatcher;
      
      private var _displayContainer:DisplayObjectContainer;
      
      private var _volume:Number;
      
      private var _videoIndex:int;
      
      private var _stageWidth:Number;
      
      private var _stageHeight:Number;
      
      private var _screenStatus:String;
      
      private var _baiduMainVideo:String;
      
      private var _disablePreroll:Boolean;
      
      private var _disableSkipAd:Boolean;
      
      private var _playerId:String;
      
      private var _videoPlayerUrl:String;
      
      private var _videoPlayerVersion:String;
      
      private var _playerUrl:String;
      
      private var _adManager;
      
      private var _playerLoader:Loader;
      
      private var _playerUrlLoader:URLLoader;
      
      private var _playerRequest:URLRequest;
      
      private var _speed:Number;
      
      private var _startTime:Number;
      
      private var _loadPlayerTimeout:uint;
      
      private var _playerTimeOutLengthsIndex:int = 0;
      
      private const PLAYER_TIMEOUT_LENGTHS:Array = new Array(10000,15000);
      
      private var _env:Object;
      
      private var _adBlockedBlackScreen:AdBlockedBlackScreen;
      
      private const IQIYI_WEB_AM_URL:String = "http://www.iqiyi.com/player/cupid/common/iamw.swf";
      
      private const IQIYI_WEBEX_AM_URL:String = "http://www.iqiyi.com/player/cupid/common/iamo.swf";
      
      private function addAdPlayerEventListeners() : void {
         this._dispatcher.addEventListener(AdPlayerEvent.VIDEO_CHANGE_SIZE,this.onChangeSize);
         this._dispatcher.addEventListener(AdPlayerEvent.VIDEO_FULLSCREEN,this.onFullscreen);
         this._dispatcher.addEventListener(AdPlayerEvent.VIDEO_NORMALSCREEN,this.onNormalscreen);
      }
      
      private function removeAdPlayerEventListeners() : void {
         this._dispatcher.removeEventListener(AdPlayerEvent.VIDEO_CHANGE_SIZE,this.onChangeSize);
         this._dispatcher.removeEventListener(AdPlayerEvent.VIDEO_FULLSCREEN,this.onFullscreen);
         this._dispatcher.removeEventListener(AdPlayerEvent.VIDEO_NORMALSCREEN,this.onNormalscreen);
      }
      
      private function onChangeSize(param1:AdPlayerEvent) : void {
         if(param1.data)
         {
            this._stageWidth = param1.data.width;
            this._stageHeight = param1.data.height;
         }
         this.resizeBlackScreen();
      }
      
      private function onFullscreen(param1:AdPlayerEvent) : void {
         this._screenStatus = "1";
      }
      
      private function onNormalscreen(param1:AdPlayerEvent) : void {
         this._screenStatus = "0";
      }
      
      public function load() : void {
         Log.info("load called");
         if((this.canShowBlackScreen()) && (AdBlockedBlackScreen.isInBlacklist(this._videoPlayerUrl)))
         {
            Log.error(this._videoPlayerUrl + ", the current video player is illegal!!");
            this.onAdBlocked(String(CupidAdPlayerConstants.PINGBACK_CODE_VIDEO_PLAYER_ILLEGAL));
            return;
         }
         this.cleanBeforeLoad();
         CupidAdPlayerUtils.callPb(
            {
               "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
               "act":"load",
               "data":this.getPingbackData()
            },this._env);
         this.loadPlayer(this._playerUrl);
      }
      
      private function loadPlayer(param1:String) : void {
         this._playerRequest = new URLRequest(param1);
         this.tryGetPlayer();
      }
      
      private function tryGetPlayer() : void {
         Log.info("load AdManager: " + this._playerRequest.url + ", time: " + (this._playerTimeOutLengthsIndex + 1));
         this.clearPlayerLoader();
         this.clearPlayerUrlLoader();
         this.clearPlayerTimeout();
         try
         {
            this._playerUrlLoader = new URLLoader();
            this._playerUrlLoader.dataFormat = URLLoaderDataFormat.BINARY;
            this.addPlayerUrlLoaderEventListeners(this._playerUrlLoader);
            this._loadPlayerTimeout = setTimeout(this.playerTimeoutHandler,this.PLAYER_TIMEOUT_LENGTHS[this._playerTimeOutLengthsIndex]);
            this._startTime = new Date().time;
            this._playerUrlLoader.load(this._playerRequest);
         }
         catch(e:Error)
         {
            Log.error("catch error while loading AdManager: " + e.message + ", " + e.getStackTrace());
            playerErrorHandler(e.message);
         }
      }
      
      private function addPlayerUrlLoaderEventListeners(param1:URLLoader) : void {
         param1.addEventListener(Event.OPEN,this.playerOpenHandler);
         param1.addEventListener(Event.COMPLETE,this.playerCompleteHandler);
         param1.addEventListener(IOErrorEvent.IO_ERROR,this.playerIOErrorHandler);
         param1.addEventListener(SecurityErrorEvent.SECURITY_ERROR,this.playerSecurityErrorHandler);
      }
      
      private function removePlayerUrlLoaderEventListeners(param1:URLLoader) : void {
         param1.removeEventListener(Event.OPEN,this.playerOpenHandler);
         param1.removeEventListener(Event.COMPLETE,this.playerCompleteHandler);
         param1.removeEventListener(IOErrorEvent.IO_ERROR,this.playerIOErrorHandler);
         param1.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,this.playerSecurityErrorHandler);
      }
      
      private function playerOpenHandler(param1:Event) : void {
         Log.info("load AdManager open");
         this.clearPlayerTimeout();
      }
      
      private function playerCompleteHandler(param1:Event) : void {
         var totalTime:Number = NaN;
         var totalKb:Number = NaN;
         var byteArray:ByteArray = null;
         var e:Event = param1;
         this.removePlayerUrlLoaderEventListeners(this._playerUrlLoader);
         try
         {
            totalTime = (new Date().time - this._startTime) / 1000;
            totalKb = this._playerUrlLoader.bytesTotal / 1024;
            this._speed = Math.round(totalKb / totalTime);
            Log.info("load AdManager complete, speed: " + this._speed + "k/s");
            byteArray = this._playerUrlLoader.data;
            this._playerLoader = new Loader();
            this._playerLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,this.playerLoadedHandler);
            this._playerLoader.loadBytes(byteArray,new LoaderContext(false,ApplicationDomain.currentDomain));
         }
         catch(error:Error)
         {
            Log.error("catch error while loading bytes:" + error.message + "," + error.getStackTrace());
            playerErrorHandler(error.message);
         }
      }
      
      private function playerLoadedHandler(param1:Event) : void {
         var msg:String = null;
         var e:Event = param1;
         Log.info("AdManager loaded");
         this._playerLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,this.playerLoadedHandler);
         try
         {
            this._adManager = e.target.content;
            if((this._adManager) && (this._adManager.hasOwnProperty("start")))
            {
               this.removeAdPlayerEventListeners();
               this._adManager.start(this._dispatcher,this._displayContainer,
                  {
                     "tvId":this._tvId,
                     "videoId":this._videoId,
                     "channelId":this._channelId,
                     "albumId":this._albumId,
                     "collectionId":this._collectionId,
                     "stageWidth":this._stageWidth,
                     "stageHeight":this._stageHeight,
                     "screenStatus":this._screenStatus,
                     "userId":this._userId,
                     "vipRight":this._vipRight,
                     "webEventId":this._webEventId,
                     "videoEventId":this._videoEventId,
                     "playerId":this._playerId,
                     "speed":this._speed,
                     "terminal":this._terminal,
                     "duration":this._duration,
                     "passportId":this._passportId,
                     "passportCookie":this._passportCookie,
                     "passportKey":this._passportKey,
                     "baiduMainVideo":this._baiduMainVideo,
                     "disablePreroll":this._disablePreroll,
                     "disableSkipAd":this._disableSkipAd,
                     "enableVideoCore":this._enableVideoCore,
                     "volume":this._volume,
                     "videoIndex":this._videoIndex,
                     "isUGC":this._isUGC,
                     "videoPlayerVersion":this._videoPlayerVersion
                  });
            }
            else
            {
               Log.error("AdManager init error:no definition");
               msg = "no_definition";
               CupidAdPlayerUtils.callPb(
                  {
                     "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
                     "act":"initerror",
                     "code":CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_INIT_ERROR,
                     "data":this.getPingbackData(msg)
                  },this._env);
               if(this.canShowBlackScreen())
               {
                  this.onAdBlocked(String(CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_INIT_ERROR),msg);
               }
               else
               {
                  this.onAdPlayerFailure();
               }
            }
         }
         catch(error:Error)
         {
            Log.error("AdManager init error: " + error.message + "," + error.getStackTrace());
            CupidAdPlayerUtils.callPb(
               {
                  "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
                  "act":"initerror",
                  "code":CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_INIT_ERROR,
                  "data":getPingbackData(error.message)
               },_env);
            onAdPlayerFailure();
         }
      }
      
      private function playerIOErrorHandler(param1:IOErrorEvent) : void {
         Log.error("load AdManager io error, time: " + (this._playerTimeOutLengthsIndex + 1));
         this.playerErrorHandler("io");
      }
      
      private function playerSecurityErrorHandler(param1:SecurityErrorEvent) : void {
         Log.error("load AdManager security error, time: " + (this._playerTimeOutLengthsIndex + 1));
         this.playerErrorHandler("security");
      }
      
      private function playerErrorHandler(param1:String) : void {
         this.clearPlayerTimeout();
         this.clearPlayerLoader();
         this.clearPlayerUrlLoader();
         if(this._playerTimeOutLengthsIndex == 0)
         {
            CupidAdPlayerUtils.callPb(
               {
                  "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
                  "act":"first_failure",
                  "data":this.getPingbackData(param1)
               },this._env);
         }
         if(this.retryGetPlayer())
         {
            return;
         }
         CupidAdPlayerUtils.callPb(
            {
               "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
               "act":"httperror",
               "code":CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_HTTP_ERROR,
               "data":this.getPingbackData(param1)
            },this._env);
         if(this.canShowBlackScreen())
         {
            this.onAdBlocked(String(CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_HTTP_ERROR),param1);
         }
         else
         {
            this.onAdPlayerFailure();
         }
      }
      
      private function onAdBlocked(param1:String, param2:String = "") : void {
         CupidAdPlayerUtils.callPb(
            {
               "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_AD,
               "act":"adblock",
               "data":this.getPingbackData(param2,param1)
            },this._env);
         this.showBlackScreen();
      }
      
      private function showBlackScreen() : void {
         Log.info("show black screen");
         this._adBlockedBlackScreen = new AdBlockedBlackScreen(this._stageWidth,this._stageHeight);
         this._adBlockedBlackScreen.addEventListener(AdBlockedBlackScreenEvent.BLACK_SCREEN_COMPLETE,this.onBlackScreenComplete);
         this._displayContainer.stage.addChild(this._adBlockedBlackScreen);
         this._adBlockedBlackScreen.show();
      }
      
      private function onBlackScreenComplete(param1:AdBlockedBlackScreenEvent) : void {
         var _loc2_:Object = null;
         this.clearBlackScreen();
         this.onAdPlayerBlock();
         if(this._dispatcher)
         {
            _loc2_ = 
               {
                  "tvId":this._tvId,
                  "videoId":this._videoId
               };
            this._dispatcher.dispatchEvent(new AdPlayerEvent(AdPlayerEvent.CONTROL_VIDEO_START,_loc2_));
            Log.info("black screen complete and control video start");
         }
      }
      
      private function resizeBlackScreen() : void {
         if(this._adBlockedBlackScreen)
         {
            this._adBlockedBlackScreen.resize(this._stageWidth,this._stageHeight);
         }
      }
      
      private function clearBlackScreen() : void {
         Log.info("clear black screen");
         if(this._adBlockedBlackScreen)
         {
            this._adBlockedBlackScreen.removeEventListener(AdBlockedBlackScreenEvent.BLACK_SCREEN_COMPLETE,this.onBlackScreenComplete);
            this._adBlockedBlackScreen.destroy();
            if(this._displayContainer.stage.contains(this._adBlockedBlackScreen))
            {
               this._displayContainer.stage.removeChild(this._adBlockedBlackScreen);
            }
            this._adBlockedBlackScreen = null;
         }
      }
      
      private function playerTimeoutHandler() : void {
         Log.error("load AdManager timeout, time: " + (this._playerTimeOutLengthsIndex + 1));
         this.clearPlayerTimeout();
         this.clearPlayerLoader();
         this.clearPlayerUrlLoader();
         if(this._playerTimeOutLengthsIndex == 0)
         {
            CupidAdPlayerUtils.callPb(
               {
                  "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
                  "act":"first_failure",
                  "data":this.getPingbackData("timeout")
               },this._env);
         }
         if(this.retryGetPlayer())
         {
            return;
         }
         CupidAdPlayerUtils.callPb(
            {
               "pbtp":CupidAdPlayerConstants.PINGBACK_TYPE_PLAYER,
               "act":"timeout",
               "code":CupidAdPlayerConstants.PINGBACK_CODE_PLAYER_TIMEOUT,
               "data":this.getPingbackData("timeout")
            },this._env);
         this.onAdPlayerFailure();
      }
      
      private function getPingbackData(param1:String = "", param2:String = "") : String {
         var _loc3_:String = CupidAdPlayerUtils.getLocation();
         var _loc4_:String = CupidAdPlayerUtils.getReferrer();
         return [param2,this._videoPlayerVersion,_loc3_,VERSION,this._playerUrl,param1,this._videoPlayerUrl,_loc4_].join("@");
      }
      
      private function clearPlayerUrlLoader() : void {
         if(this._playerUrlLoader)
         {
            this.removePlayerUrlLoaderEventListeners(this._playerUrlLoader);
            try
            {
               this._playerUrlLoader.close();
            }
            catch(e:Error)
            {
            }
            this._playerUrlLoader = null;
         }
      }
      
      private function clearPlayerLoader() : void {
         if(this._playerLoader)
         {
            this._playerLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,this.playerLoadedHandler);
            try
            {
               this._playerLoader.unloadAndStop();
               this._playerLoader.close();
            }
            catch(e:Error)
            {
            }
            this._playerLoader = null;
         }
      }
      
      private function clearPlayerTimeout() : void {
         if(this._loadPlayerTimeout)
         {
            clearTimeout(this._loadPlayerTimeout);
            this._loadPlayerTimeout = 0;
         }
      }
      
      private function retryGetPlayer() : Boolean {
         this._playerTimeOutLengthsIndex++;
         if(this._playerTimeOutLengthsIndex < this.PLAYER_TIMEOUT_LENGTHS.length)
         {
            Log.info("retry to load adplayer");
            this.tryGetPlayer();
            return true;
         }
         return false;
      }
      
      private function cleanBeforeLoad() : void {
         Log.info("clean before loading adplayer, _dispCon.numChildren=" + (this._displayContainer?this._displayContainer.numChildren:0));
         this.clearPlayerTimeout();
         this.clearPlayerLoader();
         this.clearPlayerUrlLoader();
         if(this._displayContainer)
         {
            while(this._displayContainer.numChildren > 0)
            {
               this._displayContainer.removeChildAt(0);
            }
         }
      }
      
      public function destroy() : void {
         Log.info("destroy");
         this.removeAdPlayerEventListeners();
         this.clearPlayerTimeout();
         this.clearPlayerLoader();
         this.clearPlayerUrlLoader();
         this.clearBlackScreen();
         if(this._adManager)
         {
            this._adManager = null;
         }
         if(this._dispatcher)
         {
            this._dispatcher = null;
         }
         if(this._displayContainer)
         {
            while(this._displayContainer.numChildren > 0)
            {
               this._displayContainer.removeChildAt(0);
            }
            this._displayContainer = null;
         }
      }
      
      private function onAdPlayerFailure() : void {
         var _loc1_:Object = null;
         Log.info("dispatch adplayer loading failure event");
         if(this._dispatcher)
         {
            _loc1_ = 
               {
                  "tvId":this._tvId,
                  "videoId":this._videoId
               };
            this._dispatcher.dispatchEvent(new AdPlayerEvent(AdPlayerEvent.ADPLAYER_LOADING_FAILURE,_loc1_));
         }
      }
      
      private function onAdPlayerBlock() : void {
         var _loc1_:Object = null;
         Log.info("dispatch adplayer block event");
         if(this._dispatcher)
         {
            _loc1_ = 
               {
                  "tvId":this._tvId,
                  "videoId":this._videoId
               };
            this._dispatcher.dispatchEvent(new AdPlayerEvent(AdPlayerEvent.ADPLAYER_AD_BLOCK,_loc1_));
         }
      }
      
      private function generateEnv() : Object {
         var _loc1_:Object = new Object();
         _loc1_.userId = this._userId;
         _loc1_.passportId = this._passportId;
         _loc1_.webEventId = this._webEventId;
         _loc1_.videoEventId = this._videoEventId;
         _loc1_.playerId = this._playerId;
         _loc1_.videoId = this._videoId;
         _loc1_.tvId = this._tvId;
         _loc1_.albumId = this._albumId;
         _loc1_.channelId = this._channelId;
         return _loc1_;
      }
      
      private function canShowBlackScreen() : Boolean {
         return (AdBlockedBlackScreen.CAN_SHOW) && this._vipRight == "0";
      }
      
      private function isQiyiWebEx() : Boolean {
         return this._terminal == "iqiyiwex";
      }
   }
}
